#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <cstring>
#include "socket.hpp"
#include "TcpServer.hpp"
#include "protocol.hpp"
#include "Log.hpp"

using namespace socket_ns;
using namespace protocol_ns;
void Usage()
{
    std::cout << "Please Enter:\n"
              << "\tseverip  severport";
}
int main(int argc, char *argv[])
{
    if (argc != 3)
    {
        Usage();
        exit(1);
    }
    std::string ip = argv[1];
    uint16_t port = std::stoi(argv[2]);

    // 创建套接字结构体
    InetAddr server(ip, port);

    socket_ptr sockfd = std::make_shared<TcpSocket>();
    bool res = sockfd->BuildClientSocket(server);
    while (res)
    {
        // 创建套接字
        // bool isreconnect = false;
        // int cnt = 10;

        // 请求连接
        // do
        // {
        //     if (res)
        //     {
        //         isreconnect = true;
        //         sleep(1);
        //         Log(WARNING, "already disconnect,please wait reconnect...%d", cnt--);
        //     }
        //     else
        //     {
        //         isreconnect = false;
        //         // Log(DEBUG, "connect success...");
        //     }
        // } while (isreconnect && cnt);
        // if (cnt == 0)
        // {
        //     Log(FATAL, "reconnect fail");
        //     exit(-1);
        // }
        // 开始通信

        sleep(1);
        Factory fac;
        auto req = fac.BuildRequest();
        req->Debug();
        std::string sendmessage;
        req->Serialize(&sendmessage);
        //编码
        std::string sendreq = Encode(sendmessage);
        // 发送
        sockfd->Send(sendreq);
        // 接收
        std::string recvmessage;
        // 接收
        int n = sockfd->Recv(&recvmessage);
        //std::cout<<"recvmessage:"<<recvmessage<<std::endl;
        if (n <= 0)
        {
            
            break;
        }
        // 解码
        std::string packge = Decode(recvmessage);
        if (packge.empty())
        {
            continue;
        }
        auto res = fac.BuildResponse();
        res->DeSerialize(packge);
        res->Debug();
    }
    return 0;
}